package com.xx.springboot.utils;

import com.alibaba.druid.util.StringUtils;
import jxl.Workbook;
import jxl.common.Logger;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Component;


import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * Created by xiaoxiunique on 2018-9-25.
 */
@Component
public class XlsUtils {

    private Logger logger = Logger.getLogger(XlsUtils.class);


    /**
     * 导入配置文件
     *
     * @param tpl com.km.export.tpl下的文件名
     * @return
     */
    private List<NameValuePair> loadConfig(String tpl) {
        ClassLoader classLoader = getClass().getClassLoader();
        URL resource = classLoader.getResource(tpl);
        logger.debug("resource: " + resource);
        List<NameValuePair> map = new ArrayList<>();
        System.out.println(tpl);
        try {
            List<String> readLines = FileUtils.readLines(new File(resource.getFile()), "utf-8");
            logger.debug("readLines: " + readLines);
            for (int i = 0; i < readLines.size(); i++) {
                String string = readLines.get(i);
                if (!StringUtils.isEmpty(string)) {
                    String[] split = string.split("=");
                    map.add(new NameValuePair(split[0], split[1]));
                }
            }
        } catch (Exception e) {
            logger.error("载入配置文件时报错: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("请选择正确的模板文件上传");
        }
        return map;
    }

    /**
     * 加载导出配置
     *
     * @param tpl tpl 文件
     */
    public List<NameValuePair> loadExportConfig(String tpl) {
        return loadConfig("com/xx/springboot/export/tpl/" + tpl);
    }

    /**
     * 加载导入配置
     *
     * @param tpl tpl 文件
     */
    public List<NameValuePair> loadInportConfig(String tpl) {
        return loadConfig("com/xx/springboot/inport/tpl/" + tpl);
    }

    /**
     * 获取xls模板文件
     *
     * @param tpl tpl 文件
     */
    private File loadXlsTpl(String tpl) {
        URL resource = this.getClass().getClassLoader().getResource("com/xx/springboot/export/tpl/" + tpl);
        logger.info("tpl: com/xx/springboot/export/tpl/" + tpl);
        logger.info("resource: " + resource);
        if (resource != null) {
            return new File(resource.getFile());
        } else {
            return null;
        }
    }


    /**
     * 导出生成xls文件
     *
     * @param title    sheet表单的标题
     * @param tpl      com.km.export.tpl文件模板
     * @param dataList 数据列表
     * @return File
     */
    public File outputXls(String title, String tpl, List<Object> dataList, boolean isTpl) {
        Workbook wk = null;
        WritableWorkbook workbook = null;
        File xlsFile  = null;
        try {
            // 获取配置文件
            List<NameValuePair> loadConfig = null;
            File                tplXlsFile = null;
            if (isTpl) {
                loadConfig = loadInportConfig(tpl);
            } else {
                loadConfig = loadExportConfig(tpl + ".tpl");
                tplXlsFile = loadXlsTpl(tpl + ".xls");
                boolean exists = tplXlsFile.exists();
                if (!exists) {
                    throw new RuntimeException("没有获取到配置文件，请询问系统管理员");
                }
                wk = Workbook.getWorkbook(tplXlsFile);
            }
            logger.info("获取到配置文件: " + loadConfig);

            // 输入文件

            xlsFile = File.createTempFile("export_file", "data");
            // File xlsFile = new File(outputFile);
            if (wk != null) {
                workbook = Workbook.createWorkbook(xlsFile, wk);
            } else {
                workbook = Workbook.createWorkbook(xlsFile);
            }
            WritableSheet sheet = workbook.getSheet(0);

            // 先写标题
            for (int i = 0; i < dataList.size(); i++) {
                Object pojo = dataList.get(i);
                for (int j = 0, len = loadConfig.size(); j < len; j++) {
                    NameValuePair curObj  = loadConfig.get(j);
                    String        content = "";
                    // 获取内容
                    String keyName = curObj.getKey();
                    if (keyName.contains("birthday") || keyName.equals("operDate")
                            || keyName.lastIndexOf("Date") != -1) {
                        String date = BeanUtils.getProperty(pojo, curObj.getKey());
                        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy",
                                Locale.ENGLISH);
                        SimpleDateFormat sFormat = new SimpleDateFormat("yyy-MM-dd HH:mm:ss", Locale.ENGLISH);
                        Date d;
                        try {
                            d = dateFormat.parse(date);
                            String dd    = sFormat.format(d);
                            Label label = new Label(j, i + 1, dd);
                            sheet.addCell(label);
                        } catch (ParseException e) {
                            Label label = new Label(j, i + 1, date);
                            sheet.addCell(label);
                        } catch (NullPointerException e) {
                            // System.out.println("nullpointerExceptin");
                        }

                    } else {
                        try {
                            content = BeanUtils.getProperty(pojo, curObj.getKey());
                        } catch (Exception e) {
                            // content = e.getMessage();
                            content = "";
                            e.printStackTrace();
                        }
                        String re = "^\\-?([1-9]\\d*|0)(\\.\\d{1,5})$"; // 验证是否是小数数字
                        if (!StringUtils.isEmpty(content) && content.matches(re)) {
                            // 过滤多余的小数位数或者000 保留两位小数
                            content = new BigDecimal(content).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                        }
                        Label label = new Label(j, i + 1, content); // 加入表格
                        sheet.addCell(label);
                    }
                }
            }
            workbook.write();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (WriteException | IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return xlsFile;
    }
}
